@include "/home/x_liwei/global/mywork/EMTO5.70/EMTO-IPG-v0.9.3a/src/function.awk"

function dealInput(Line,LoopArray,__varend__,LoopLevel,pName,compressArray,param)
{
#{{{deal with the input file
	if(Line!~/^ *#+/)
	{
		if(__Debug__>=1)_message("d","fuc: +:dealInput:-")
		
		gsub(/ +#+.*$/,"",Line)	
		if(Line~/ *L.*:.*/)
		{	
				
				if(__Debug__>1)print "Line="Line
				LoopLevel=gensub(/.*([[:digit:]]+):.*=.*/,"\\1","",Line)
				if(__Debug__>1)print "LoopLevel="LoopLevel
				param=gensub(/.*: *([^[:digit:]+] *)/,"\\1","",Line)
				if(__Debug__>1)print "param="param
				pName=gensub(/ *=.*/,"","",param)
				if(__Debug__>1)print "pName="pName
				if(__Debug__>1)print _X("-",100)

				getParamters(param,compressArray)

				if(__Debug__>1)_printarray(compressArray,"compressArray")
				if(__Debug__>1)print "finish getParamters"
			
				for(i in compressArray)LoopArray[LoopLevel][pName][i]=compressArray[i]	
				
				delete compressArray
		}
		else if(Line ~/ *SUBL *=.*/)
		{
				gsub(/#+.*$/,"",$2)	
				SUBLstr=$2
				if(__Debug__>1)print "Line="Line
				if(__Debug__>1)print "SUBLstr="SUBLstr

		}
		else if(Line~/ *SPLT *=.*/)
		{
				gsub(/#+.*$/,"",$2)	
				SPLTstr=$2	
				if(__Debug__>1)print "Line="Line
				if(__Debug__>1)print "SPLTstr="SPLTstr
		}
		else
		{
				gsub(/ /,"",$1)	
				gsub(/#+.*$/,"",$2)	
				gsub(/ /,"",$2)	
				rva[$1]=$2
				if(__Debug__>1)print "Line="Line
				if(__Debug__>1)print "rva["$1"]="rva[$1]
		}	
	}
	#}}}
}

function corePart(__varend__,i,j,count,checkecloop)
{
		#{{{ prepare for run the loopInput 
		#if(isarray(LoopArray)){for(i in LoopArray){for(j in LoopArray[i]){_printarray(LoopArray[i][j],"LoopArray["i"]["j"]") } } } 
		_message("m","finish read inputfile +wu:"FILENAME"")	
		
		if("IBZ" in rva){ if(rva["IBZ"] ~ /[[:digit:]]{1,2}/){IBZexist=1}}
		#print "IBZexist="IBZexist
		
		#if("MYPATH" in rva && rva["MYPATH"]!="" && rva["MYPATH"] !~ / */)
		if("MYPATH" in rva) 
		{
				if(__Debug__>1)_message("d","MYPATH is not empty and not in loop")
			   	rva["MYPATH"]=MyPath(rva["MYPATH"])
		}
		else
		{rva["MYPATH"]="./"}

				if(__Debug__>1)_message("d","MYPATH="rva["MYPATH"]"")

		total=1
		for(i in LoopArray)
		{	
				count=0
				for(j in LoopArray[i])
				{
						count++
						if(count==1)
						{checkecloop=_size(LoopArray[i][j])}
						else 
						{if(checkecloop!=_size(LoopArray[i][j])){_message("e","LoopLevel +:"i":- of inputfile +:"FILENAME":- # of element in earch Paramter are not same check!\n +R:STOP!!!");exit 1}}	
						if("IBZ" in LoopArray[i])IBZinLoopArray=1
						if(j=="STR")
						{
								for(k=1;k<=checkecloop;k++)
								{
										rva["STR"]=LoopArray[i][j][k]	
										SetPath("KGRN")
										"[ -e "FOR001" ] && echo 1 || echo 0"|getline FOR001exist
										close("[ -e "FOR001" ] && echo 1 || echo 0")
										if(FOR001exist)
										{
												""latPath" "FOR001"" |getline LATv 
												close(""latPath" "FOR001"")
												if(LATv!~/[[:digit:]]{1,2}/){_message("m","getLAT not work! try use IBZ settings in "FILENAME"")}
										}
										else
										{
												_message("m",":-"FOR001" +r:not exist!")
												#_message("m",":-"FOR001" +r:not exist! +g:don't forget it before run kgrn_cpa\ntry use IBZ settings in +u:"FILENAME"")
										}


										if(IBZinLoopArray)
										{ rva["IBZ"]=LoopArray[i]["IBZ"][k] }
										else 
										{if(!IBZexist && !LATv){_message("e","you did not set IBZ in "FILENAME" +R:STOP!");exit 1}}


										if(1<=LATv && LATv<=14)
										{
												if(rva["IBZ"]!="")
												{if(LATv!=rva["IBZ"]){_message("e","IBZ setting in "FILENAME" rva[IBZ]="rva["IBZ"]" not the same as "FOR001" LATv="LATv"");exit 1}}
												else
												{rva["IBZ"]=LATv}		
										}

										if(rva["IBZ"]==""){_message("e","rva[\"IBZ\"] is blank! stop!");exit 1}
										LoopArray[i]["IBZ"][k]=rva["IBZ"]	

								}

							rva["STR"]=""
							rva["IBZ"]=""
						}
				}

				SizeLoopArray[i]=checkecloop
				total=total*checkecloop
		}

		for(i=1;i<=_size(LoopArray);i++){FullName=(FullName)"L"i"-:VL"i";"};gsub(/;+$/,"",FullName);FullName0=FullName

		LP["stoprec"]=_size(LoopArray)
		LP["depth"]=0
		LP["count"]=0

		#_printarray(LP,"LP")

		_message("m","start to generate "total"X2 (scf & fcd) files ...")	
		
		loopInput(LoopArray,SizeLoopArray,LP)
						system("cp -f "runPath" "rva["MYPATH"]"")
						close("cp -f "runPath" "rva["MYPATH"]"")

		delete rva
		delete va
		delete LoopArray
		delete SizeLoopArray

		_message("m","Complete job for inputfile +wu:"FILENAME".")	
		_message("m", _X("-",50))	
#}}}
}

function loopInput(LoopArray,SizeLoopArray,LP,__varend__,i,j,k,r,jj,size,rex,rep)
{
		#{{{recursion loop for impliment the Loop Level of the inputfile 
		LP["depth"]=LP["depth"]+1

				for(j=1;j<=SizeLoopArray[LP["depth"]];j++)
				{
						rex="(L"LP["depth"]")-[[:digit:]]*:"
						rep="\\1-"j":"
						FullName=gensub(rex,rep,"",FullName)
						FullName0=gensub(rex,rep,"",FullName0)
						SurName=FullName0

						for(k in LoopArray[LP["depth"]])
						{
								if(k=="MAT")
								{
										split(LoopArray[LP["depth"]][k][j],ta1,":")
										rva["MAT"] =ta1[1]; rva["SUBL"]=ta1[2]; rva["SPLT"]=ta1[3]

										maxmnta=mnta(rva["MAT"])
										num_part=split(rva["MAT"],mat,"|") 

										split(rva["SUBL"],subl,"|")
										split(rva["SPLT"],spl ,"|")

										rva["NT"]=0															#|
										split(gensub(/\|/," ","g",rva["SUBL"]),maxsubarray," ")				#|--get the "NT"  rvalue.
										for(jj in maxsubarray){rva["NT"]=_max(maxsubarray[jj],rva["NT"])}	#|
								}
								else
								{ rva[k]=LoopArray[LP["depth"]][k][j] }
								
								if("STR" in LoopArray[LP["depth"]])
								{ SetPath("KGRN"); SetPath("KFCD") }			#if IBZ in LoopArray, it must be the same level as STR		

								#if("MYPATH" in LoopArray[LP["depth"]])
								#{
										##_message("d","MYPATH is in Loop")
										#rva["MYPATH"]=MyPath(rva["MYPATH"])
								#}

								rex="VL"LP["depth"]; rep=k"-"rva[k](rex); sub(rex,rep,FullName)

						}

						if(LP["depth"]<LP["stoprec"]){loopInput(LoopArray,SizeLoopArray,LP)}
						if(LP["depth"]==LP["stoprec"])
						#{{{in the last Level of the loops 
						{
								LP["count"]++
									
								FullName1=FullName
								gsub(/VL[[:digit:]]+/,"",FullName1)
								gsub(/;|:VL[[:digit:]]+/,"",SurName)
								MidName=LP["count"]"%"total
								if(__Debug__>1)_message("d","3:FullName="FullName1" SurName="SurName" MidName="MidName"")
								rva["SurName"]=SurName
								rva["MidName"]=MidName
								rva["FullName"]=FullName1
								
								jobName()
								
								#_message("d","JOBNAM="JOBNAM"")
								
								if(__Debug__>1)
								{
										_message("d","this is the "LP["count"]" of "total":")
										#_printarray(rva,"rva")
										_printarray(mat,"mat")
										_printarray(maxsubarray,"maxsubarray")
										_printarray(subl,"subl")
										_printarray(spl,"spl")
								}
										va["JOBNAM"]=JOBNAM

										JOBNAM=rva["MYPATH"]JOBNAM

								#_message("d","JOBNAM="JOBNAM"")
								
								for(r in rva){va[r]=rva[r]}	

								outKGRN(JOBNAM".scf")

								outKFCD(JOBNAM".fcd")

						}
						#}}}

						i=LP["depth"]
						rex="L"i"-([[:digit:]]+):.*VL"i
						rep="L"i"-\\1:VL"i
						FullName=gensub(rex,rep,"",FullName)
				}

		LP["depth"]=LP["depth"]-1

		return 0
		#}}}		
}

function expandAlloyName(AlloyName,CompArray,isalloy,__varend__,LoopLevel,i,j,k,SubAlloyStr,seqStr,EleName,EleArray,SubAlloyArray,ExpEleArray,LP,checkecloop,count)
{
		#{{{if [ ] or ( ) in AlloyName, use this function to expand it
		#eg. Cu(10,5,25:1)Au   or Cu[10 15 20 25:1]Au

#{{{pre-process the AlloyName: after ] or ) insert a "," ; insert a "?" for element who is not set concentration, and store in array EleArray
	gsub(/\)/,"),",AlloyName); gsub(/\]/,"],",AlloyName) #;gsub(/,+ *$/,"",AlloyName)
	AlloyName=gensub(/,+([[:alnum:]]*)$/,"\\1","g",AlloyName)
	if(__Debug__>1)print "1 AlloyName="AlloyName

if(isalloy)
{
	AlloyName=gensub(/([[:lower:]])([[:upper:]])/,"\\1?\\2","g",AlloyName)
	AlloyName=gensub(/([[:upper:]])([[:upper:]])/,"\\1?\\2","g",AlloyName)
}	
	if(__Debug__>1)print "2 AlloyName="AlloyName
	EleNu=split(AlloyName,EleArray,",")
#}}}	
	
	for(i=1;i<=EleNu;i++){SubAlloyStr=SubAlloyStr"%"i"%,"};gsub(/,+$/,"",SubAlloyStr)
	if(__Debug__>1)print "SubAlloyStr="SubAlloyStr
	if(__Debug__>1)_printarray(EleArray,"EleArray")

#{{{get LoopLevel information & store in Array ExpEleArray[LoopLevel][ele#][loop_index_of_ele]
	for(i=1;i<=EleNu;i++)
	{
			LoopLevel=gensub(/.*:(.*)[\)\]].*/,"\\1","g",EleArray[i])	; if(__Debug__>1)print "LoopLevel="LoopLevel	
			seqStr   =gensub(/.*[\(\[]|:.*[\)\]].*/,"","g",EleArray[i]) ; if(__Debug__>1)print "seqStr="seqStr
			sub(/-[fF] */,"",seqStr)									; if(__Debug__>1)print "sub seqStr="seqStr
			EleName=gensub(/[\(\[].*[\)\]]/,"%","g",EleArray[i])		; if(__Debug__>1)print "EleName="EleName

			#print "start..EleArray["i"]="EleArray[i]
			if(EleArray[i] ~/.*-[fF].*/ )
			{
					"awk '{printf \"%s \" ,$0}' "seqStr"" | getline seqStr1 
					close( "awk '{printf \"%s \" ,$0}' "seqStr"" )
					sub(/ +$/,"",seqStr1);seqStr=seqStr1
			}
			else
			{
					if(index(EleArray[i],"("))
					{seqStr=_seq(seqStr,"[ ,]")}
			}
			
			#print "ok..."
			ExpEleArray[LoopLevel][i][1]=""
			split(seqStr,ExpEleArray[LoopLevel][i]," ")
			_subarray("%",ExpEleArray[LoopLevel][i],EleName)
	}
#}}}

	for(i in ExpEleArray){ for(j in ExpEleArray[i]) { if(__Debug__>1){_printarray(ExpEleArray[i][j],"ExpEleArray[+:"i":-][+:"j":-]")};for(k in ExpEleArray[i][j]){SubAlloyArray[i][k]=SubAlloyStr} } }

#{{{compress ExpEleArray into SubAlloyArray: SubAlloyArray[LoopLevel][expanded_ele_info_index] & will use it in recursion loop
	for(i in ExpEleArray)
	{
			count=0
				for(j in ExpEleArray[i]) 
				{
					count++
					if(count==1){checkecloop=_size(ExpEleArray[i][j])}
					else{if(checkecloop!=_size(ExpEleArray[i][j])){_message("e","LoopLevel +:"i":- # not same, +R:STOP!!:-");exit 1}}
					for(k in ExpEleArray[i][j]){SubAlloyArray[i][k]=gensub("%"j"%",ExpEleArray[i][j][k],"",SubAlloyArray[i][k])}
				}
				if(__Debug__>1)_printarray(SubAlloyArray[i],"SubAlloyArray[+:"i":-]")
	}
#}}}

		LP["stoprec"]=_size(SubAlloyArray)
		LP["depth"]=0
		LP["count"]=0
		LP["EleNu"]=EleNu
		
		if(__Debug__>1)sindex="   "
		loopAlloy(SubAlloyArray,LP,CompArray,isalloy)
		delete compersition

		if(__Debug__>1)_printarray(CompArray,"CompArray")
#}}}
}

function loopAlloy(LoopArray,LP,CompArray,isalloy,__varend__,i,j,k,t1a,sum,sumArray,size)
{
#{{{recursion loop for impliment the Loop Level in expandAlloyName
		LP["depth"]=LP["depth"]+1

		size=_size(LoopArray[LP["depth"]])
		#for(i in LoopArray[LP["depth"]])
		for(i=1;i<=size;i++)
		{	
				if(__Debug__>1)expr="(^.{"LP["depth"]-1"}).(.*)"
				if(__Debug__>1)repl="\\1"i"\\2"
				if(__Debug__>1)sindex=gensub(expr,repl,"g",sindex)	

				split(LoopArray[LP["depth"]][i],t1a,",")
				for(j in t1a)
				{
						if(t1a[j]!~/%.*/) compersition[j]=t1a[j]		
				}

				if(LP["depth"]<LP["stoprec"]){loopAlloy(LoopArray,LP,CompArray,isalloy)}
#{{{in the last Level of the loops compress the all info into a 1D array CompArray[alloy_index]				
				if(LP["depth"]==LP["stoprec"])
				{
						LP["count"]++

						for(k=1;k<=LP["EleNu"];k++)CompArray[LP["count"]]=CompArray[LP["count"]]compersition[k]
					
					if(isalloy)
					{
						CompArray[LP["count"]]=completeAlloy(CompArray[LP["count"]])	
					}	
						if(__Debug__>1)printf("Total: %3d index: %s compersition: %s \n",LP["count"],sindex,CompArray[LP["count"]])
				}
#}}}				
		}

		LP["depth"]=LP["depth"]-1

		return 0
#}}}		
}

function completeAlloy(alloyName,__varend__,ta1,sum,sumArray,size,i)
{# "?" for unknown concentration & "|" for seperate different compersitions
#{{{complete the total concentration of the alloy equal to 100%
		size=split(alloyName,ta1,"|")	

		for(i in ta1)
		{
				split(ta1[i],sumArray,/[[:alpha:]\?]+/)	
				sum=100-_Nsumarray(sumArray)	
				if(sum<0||sum>100){_message("e","compersition does not exist: +:"ta1[i]":- in +:"alloyName":-")}
				gsub(/\?/,sum,ta1[i])
		}
		alloyName=""
		for(i=1;i<=size;i++)
		{
				alloyName=(alloyName)ta1[i]"|"
		}
		sub(/\|+$/,"",alloyName)
		return alloyName
#}}}
}

function getParamters(param,compressArray,__varend__,i,j,ParaArray,sizePA,isalloy,CArray,sublta1,sublta2,splta1,sublta1size,sublta2size)
{# ";" for seperate 
		#{{{store all values of one single paramter in a array
		
		if(__Debug__>=1)_message("d","fuc: +:getParamters:-")
		gsub(/ *;+ */,";",param) ; gsub(/ *\|+ */,"|",param)
		pName=gensub(/ *=.*/,"","",param)

		if(pName=="MAT")
		#if(pName~/ *MAT */)
		{		
				isalloy=1
				if(__Debug__>1)print "SUBLstr="SUBLstr, "SPLTstr="SPLTstr

				sublta1size=split(SUBLstr,sublta1,";")
				if(__Debug__>1)_printarray(sublta1,"sublta1")
				split(SPLTstr,splta1,";")
				for(i=1;i<=sublta1size;i++)
				{
					gsub(/)/,"),",sublta1[i]) ;	gsub(/\]/,"],",sublta1[i])	
					gsub(/,+/,",",sublta1[i]) ; gsub(/,$/,"",sublta1[i])	
					if(__Debug__>1)_printarray(sublta1,"sublta1")
					
					sublta2size=split(sublta1[i],sublta2,",")
					if(__Debug__>1)_printarray(sublta2,"sublta2")
					sublta1[i]=""	
					for(j=1;j<=sublta2size;j++)	
					{
							seqstr=gensub(/.*[\(\[](.*)[\)\]].*/,"\\1","",sublta2[j])
							if(__Debug__>1)_message("d","1seqstr="seqstr"|")	
							if(index(sublta2[j],"("))seqstr=_seq(seqstr," ")
							if(__Debug__>1)_message("d","2seqstr="seqstr"|")	
							   if(__Debug__==1)_message("d","sublta2["j"]="sublta2[j])
							   gsub(/[\(\[].*[\)\]]/,seqstr,sublta2[j])
							   if(__Debug__==1)_message("d","sublta2["j"]="sublta2[j])
							   gsub(/\| */,"|",sublta2[j])
							   if(__Debug__==1)_message("d","sublta2["j"]="sublta2[j])
							sublta1[i]=sublta1[i]" "sublta2[j]		
					}

				}
		}

		if(__Debug__>1)print "pName="pName
		sub(/.*= */,"",param)

		sizePA=split(param,ParaArray,";")

		if(__Debug__>1)_printarray(ParaArray,"ParaArray")
		for(i=1;i<=sizePA;i++)
		{
				if(ParaArray[i]~/.*[\(\[].*/)
				{
					expandAlloyName(ParaArray[i],CArray,isalloy)	   
				}
				else
				{
						split(ParaArray[i],CArray,"|")
						if(isalloy){for(cc in CArray){if( checkAlloy(CArray[cc]))exit 1}}
						delete CArray; CArray[1]=ParaArray[i]
						#_message("d","concentration is ok")
				}

				if(pName=="MAT")
				#if(pName~/ *MAT */)
				{
						_subarray("^",CArray,":"sublta1[i])
						_subarray("^",CArray,":"splta1[i])
				}

				_appendArray(compressArray,CArray)

				delete CArray	   
		}
		pName=pName"="
		#_subarray("$",compressArray,pName)

		#}}}
}

function checkAlloy(Alloy,__varend__,sumArray,sum)
{
#{{{check the total concentration of alloy equal to 100%
	split(Alloy,sumArray,/[[:alpha:]]+/)
	sum=_Nsumarray(sumArray)	
	if(sum!=100){_message("e","total concentration of +:"Alloy":- "sum" is not 100%");return 1}
	return 0
#}}}
}
function jobName(__varend__,preName,rex,n,i,Name,jnarray,str)
{
		#{{{
		if(__Debug__>=1)_message("d","fuc: +:jobName:-")
		if(__Debug__>1)_message("d","rva[+:job:-]="rva["job"]"")

		if(!("job" in rva)||rva["job"]==""||rva["job"]~/ +/)	
		{
			if(__Debug__>1)_message("d","rva[+:job:-] not set, use SurName:"SurName" for JOBNAM")
				JOBNAM=SurName
		}
		else if(index(rva["job"],"%"))
		{
				#preName=gensub(/(^[^-]*)-.*/,"\\1","g",rva["job"])
				preName=gensub(/(^[^%]*)%.*/,"\\1","g",rva["job"])
				str=rva["job"]
				#gsub(/.*-%/,"",str)
				rex="^"preName"%"
				gsub(rex,"",str);gsub(/%+/,"%",str)
				#_message("d","preName="preName" str="str"")
				JOBNAM=preName
				#JOBNAM=preName"-"
				n=split(str,jnarray,"%")
				for(i=1;i<=n;i++)
				{
						name=jnarray[i]
						if(name in rva)
						{
								str=(name)rva[name]
								sub(/$/,str,JOBNAM);gsub(name,"-",JOBNAM)
						}
						else
						{_message("e",""Name" is not in rva[]");exit 1}	

				}
			if(__Debug__>1)_message("d","have % use custome JOBNAM="JOBNAM"")

		}
		else
		{
				JOBNAM=rva["job"]
			if(__Debug__>1)_message("d","not have -% use custome JOBNAM:"JOBNAM"")
		}
				JOBNAM=(JOBNAM)"_"MidName;gsub(/\||-+/,"-",JOBNAM);gsub(/^-+/,"",JOBNAM)
			if(__Debug__>1)_message("d","have % use custome1 JOBNAM="JOBNAM"")
#}}}
}

function MyPath(Path,__vend__,i,n,TPath,PathArray,folderexist)
{
#{{{create folders in the Path
		sub(/\/+ *$/,"",Path);gsub(/\/+/,"/",Path);gsub(/~/,ENVIRON["HOME"]"/",Path)
		n=split(Path,PathArray,"/")
		for(i=1;i<=n;i++)
		{
				if(i==1)
				{TPath=PathArray[i]}
				else
				{TPath=TPath"/"PathArray[i]}

				if(PathArray[i]!="~" || PathArray[i]!~/\.{1,2}/)
				{
						command="[ -d "TPath" ] && echo 1 || echo 0"
						command|getline folderexist
						close(command)
						if(!folderexist)
						{system("mkdir "TPath"")}
				}

		}

		TPath=gensub(/\/|\.+|~| */,"","",Path)
		_message("d","TPath="TPath"")
		if(TPath~/[[:alnum:]]+/)
		{return Path"/"}
		else
		{return ""}
		#}}}
}

function outKGRN(OFileName)
{
		#{{{output KGRN input file
		SetPath("KGRN")

		system("rm -f "OFileName"")

		printf "%4s%56s\n","KGRN",strftime("%d %b %y")  >>OFileName
		printf "JOBNAM=%-s\n",va["JOBNAM"]  >>OFileName
		printf "STRT..=%3s MSGL.=%3d EXPAN.=%2s FCD..=%3s FUNC..=%4s\n",\
			   v(va["STRT"],"A"),v(va["MSGL"],0),v(va["EXPAN"],"S"),\
			   v(va["FCD"],"Y"),v(va["FUNC"],"SCA")>>OFileName
		printf "FOR001=%s\n",FOR001>>OFileName
		printf "FOR001=%s\n",FOR001>>OFileName
		printf "DIR002=pot/\n">>OFileName
		printf "DIR003=pot/\n">>OFileName
		printf "FOR004=%s\n",FOR004>>OFileName
		printf "DIR006=%s\n",v(va["DIR006"],"") >>OFileName
		printf "DIR009=pot/\n" >>OFileName
		printf "DIR010=chd/\n" >>OFileName
		printf "DIR011=/tmp/\n" >>OFileName
		printf "Self-consistent KKR calculation for %s\n",\
			   v(va["explain"],va["STR"]" "va["MAT"])>>OFileName
		printf "Band: 10 lines\n" >>OFileName
		printf "NITER.=%3d NLIN.=%3d NPRN.=%3d NCPA.=%3d NT...=%3d MNTA.=%3d\n",\
				  v(va["NITER"],500),v(va["NLIN"],31),v(va["NPRN"],0),v(va["NCPA"],11),\
				  v(va["NT"],NT),v(va["MNTA"],maxmnta)>>OFileName
		printf "MODE..=%3s FRC..=%3s DOS..=%3s OPS..=%3s AFM..=%3c CRT..=%3s\n",\
				  v(va["MODE"],"3D"),v(va["FRC"],"N"),v(va["DOS"],"N"),v(va["OPS"],"N"),\
				  v(va["AFM"],"F"),v(va["CRT"],"M") >>OFileName
		printf "Lmaxh.=%3d Lmaxt=%3d NFI..=%3d FIXG.=%3d SHF..=%3d SOFC.=%3s\n",\
				  v(va["Lmaxh"],8),v(va["Lmaxt"],4),v(va["NFI"],31),v(va["FIXG"],2),\
				  v(va["SHF"],0),v(va["SOFC"],"Y")>>OFileName
		printf "KMSH...=%2s IBZ..=%3d NKX..=%3d NKY..=%3d NKZ..=%3d FBZ..=%3s\n",\
			   v(va["KMSH"],"G"),v(va["IBZ"],ibz[struct[ss]]),v(va["NKX"],13),\
			   v(va["NKY"],13),v(va["NKZ"],13),v(va["FBZ"],"N") >>OFileName
		printf "KMSH2..=%2s IBZ2.=%3d NKX2.=%3d NKY2.=%3d NKZ2.=%3d\n",\
				  v(va["KMSH2"],"G"),v(va["IBZ2"],1),v(va["NKX2"],4),v(va["NKY2"],0),\
				  v(va["NKZ2"],51)>>OFileName
		printf "ZMSH...=%2s NZ1..=%3d NZ2..=%3d NZ3..=%3d NRES.=%3d NZD.=%4d\n",\
				  v(va["ZMSH"],"C"),v(va["NZ1"],16),v(va["NZ2"],16),v(va["NZ3"],8),\
				  v(va["NRES"],4),v(va["NZD"],200)>>OFileName
		printf "DEPTH..=%7.3f IMAGZ.=%7.3f EPS...=%7.3f ELIM..=%7.3f\n",\
			   v(va["DEPTH"],1),v(va["IMAGZ"],0.02),v(va["EPS"],0.2),\
			   v(va["ELIM"],-1) >>OFileName
		printf "AMIX...=%7.3f EFMIX.=%7.3f VMTZ..=%7.3f MMOM..=%7.3f\n",\
			   v(va["AMIX"],0.03),v(va["EFMIX"],1.0),v(va["VMTZ"],0),\
			   v(va["MMOM"],0) >>OFileName
		printf "TOLE...= %6s TOLEF.= %6s TOLCPA= %6s TFERMI=%7.2f (K)\n",\
			   v(va["TOLE"],"1.d-07"),v(va["TOLEF"],"1.d-07"),\
			   v(va["TOLCPA"],"1.d-06"),v(va["TFERMI"],500.0)>>OFileName
		printf "SWS......=%10.6f NSWS.=%3d DSWS..=%7.2f ALPCPA=%7.4f\n",\
			   v(va["SWS"],2.6),v(va["NSWS"],1),v(va["DSWS"],0.05),\
			   v(va["ALPCPA"],0.902) >>OFileName
		printf "Setup: 2 + NQ*NS lines\n" >>OFileName
		printf "EFGS...=%7.3f HX....=%7.3f NX...=%3d NZ0..=%3d STMP..=%2s\n",\
			   v(va["EFGS"],0),v(va["HX"],0.1),v(va["NX"],5),v(va["NZ0"],6),\
			   v(va["STMP"],"N")>>OFileName
		printf "Symb   IQ IT ITA NZ  CONC   Sm(s)  S(ws) WS(wst) QTR SPLT\n">>OFileName

		outInfoMAT(OFileName) 

		printf "Atom:  4 lines + NT*NTA*6 lines\n">>OFileName	
		printf "IEX...=%3d NP..=%4d NES..=%3d NITER=%3d IWAT.=%3d NPRNA=%3d\n",\
				  v(va["IEX"],4),v(va["NP"],251),v(va["NES"],15),v(va["NITER"],100),\
				  v(va["IWAT"],0),v(va["NPRNA"],0)>>OFileName
		printf "VMIX.....=%10.6f RWAT....=%10.6f RMAX....=%10.6f\n",\
			   v(va["VMIX"],0.3),v(va["RWAT"],3.5),v(va["RMAX"],20)>>OFileName
		printf "DX.......=%10.6f DR1.....=%10.6f TEST....=%10s\n",\
				  v(va["DX"],0.03),v(va["DR1"],0.002),v(va["TEST"],"1.00E-12")>>OFileName
		printf "TESTE....=%10s TESTY...=%10s TESTV...=%10s\n",\
				  v(va["TESTE"],"1.00E-12"),v(va["TESTY"],"1.00E-12"),v(va["TESTV"],"1.00E-12")>>OFileName

		outInfoAtom(OFileName)

		print "FullName="FullName1" SurName="SurName" MidName="MidName"" >>OFileName
		return 0
		#}}}		
}

function outKFCD(OFileName)
{
		#{{{output KFCD input file
		SetPath("KFCD")		
		system("rm -f "OFileName"")
		
		printf "%-9s MSGL..=%3d %39s\n","KFCD",v(va["MSGL"],0),\
			   strftime("%d %b %y")>OFileName
		printf "JOBNAM...=%-s\n",va["JOBNAM"]>>OFileName
		printf "STRNAM...=%-s\n",STRNAM>>OFileName
		printf "DIR001="DIR001"\n">>OFileName
		printf "DIR002="DIR002"\n">>OFileName
		printf "DIR003="DIR003"\n">>OFileName
		printf "DIR004="DIR004"\n">>OFileName
		printf "DIR006=./\n">>OFileName
		printf "Lmaxs.= 30 NTH..= 41 NFI..= 81 FPOT..= N\n",\
			   v(va["Lmaxs"],30),v(va["NTH"],41),v(va["NFI"],81),\
			   v(va["FPOT"],"N")>>OFileName
		printf "OVCOR.=%3s UBG..=%3s NPRN.=%3d\n",v(va["OVCOR"],"Y"),\
			   v(va["UBG"],"N"),v(va["NPRN"],0)>>OFileName
		printf "%s",v(va["cpa"],"")>>OFileName

		print "FullName="FullName1" SurName="SurName" MidName="MidName"" >>OFileName
		return 0
		#}}}		
}

function outInfoMAT(OFileName,__varend__,ii,w,e,subv,element,concentration,number_position,num_site,num_split)
{
		#{{{generate the concentration part of the KGRN input file 		
		delete InfoSubl	
		#delete concentration
		for (ii=1;ii<=num_part;ii++)#loop compersition 
		{
				mat[ii]=gensub(/([[:alpha:]]+)([[:digit:]]+[\.]?[[:digit:]]*)/,"\\1%\\2#","g",mat[ii])
				gsub(/#$/,"",mat[ii])

				element[ii][1]=""; concentration[ii][1]=""; splt[ii][1]=""; sublat[ii][1]=""

				divide(mat[ii],element[ii],concentration[ii],"#","%")
				num_split=split(spl[ii],splt[ii]," ")
				num_site=split(subl[ii],sublat[ii]," ")

				if (totsp!=num_split){_message("e","+r:SPLIT:- does not fit system\nEMTO stopped");exit 1}
				if (_Nsumarray(concentration[ii])!=1 && _Nsumarray(concentration[ii])!=100)
				{_message("e","+r:The total of concentration:- is not +r:"1":- or +r:"100":-\n"mat[ii]"\n"concentration[ii][1]"\n"concentration[ii][2]"\n+wR:EMTO STOP!:-");_printarray(concentration[ii],"concentration["ii"]");exit 1}
				for (w=1;w<=num_site;w++)#loop site
				{
						for(e=1;e<=totsp;e++)#loop element
						{
								subv=sublat[ii][w]
								InfoSubl[subv][e]=element[ii][e]
								printf "%-2s%7d%3d%3d%4d%7.2f%7.3f%7.3f%7.3f%5.1f%5.1f\n",\
										  element[ii][e],w+number_position,sublat[ii][w],e,NZ[element[ii][e]],\
										  concentration[ii][e],1,1,1,0,splt[ii][e] >>OFileName             
						}#end loop element
				}#end loop site
				number_position=number_position+num_site 
		}#end loop compersition
		return 0
		#}}}		
}

function outInfoAtom(OFileName,comma,i,j,ele,maxinsub)
{
		#{{{generate atomcfg part of KGRN input file		
		delete maxinsub
		for(i=1; i<=va["NT"]; i++){for(j in InfoSubl[i]){maxinsub[i]++}}

		for(i=1; i<=va["NT"]; i++)
		{
				#END{for(i=1;i<=6;i++){print atom["Au"][i]}}
				for(j=1; j<=maxinsub[i]; j++)
				{
						#comma="grep -A 5  ^"InfoSubl[i][j]"$ ./atom.cfg"
						#while ((comma|getline ele)>0){print ele >>OFileName}
						#close(comma)
						ele=InfoSubl[i][j]
						for(k=1;k<=6;k++){print atom[ele][k]>>OFileName}
						#print atom0[ele]>>OFileName
				}
		}
		return 0
		#}}}		
}

function checkPar(CheckSTR,__varend__,i,CheckArray)
{
		#{{{check input paramters is/not of standard EMTO input file		
		CheckSTR="JOBNAM= ;STRT= ;MSGL= ;EXPAN= ;FCD= ;FUNC= ;FOR001= ;FOR001= ;DIR002= ;DIR003= ;FOR004= ;DIR006= ;DIR009= ;DIR010= ;DIR011= ;NITER= ;NLIN= ;NPRN= ;NCPA= ;NT= ;MNTA= ;MODE= ;FRC= ;DOS= ;OPS= ;AFM= ;CRT= ;Lmaxh= ;Lmaxt= ;NFI= ;FIXG= ;SHF= ;SOFC= ;KMSH= ;IBZ= ;NKX= ;NKY= ;NKZ= ;FBZ= ;KMSH2= ;IBZ2= ;NKX2= ;NKY2= ;NKZ2= ;ZMSH= ;NZ1= ;NZ2= ;NZ3= ;NRES= ;NZD= ;DEPTH= ;IMAGZ= ;EPS= ;ELIM= ;AMIX= ;EFMIX= ;VMTZ= ;MMOM= ;TOLE= ;TOLEF= ;TOLCPA= ;TFERMI= ;SWS= ;NSWS= ;DSWS= ;ALPCPA= ;EFGS= ;HX= ;NX= ;NZ0= ;STMP= ;IEX= ;NP= ;NES= ;NITER= ;IWAT= ;NPRNA= ;VMIX= ;RWAT= ;RMAX= ;DX= ;DR1= ;TEST= ;TESTE= ;TESTY= ;TESTV= "
		CheckSTR=CheckSTR";job= ;MAT= ;SPLT= ;SUBL= ;cpa= ;STR= ;="
		_dictionary(CheckSTR,CheckArray,";","=")

		for( i in rva) { if( ! (i in CheckArray) ){_message("e","+r:"i":- is not standard in EMTO\nEMTO STOP!!!!");exit 1} }
		return 0
		#}}}		
}

function mnta(string,xxnum_ele1,array,brray,i,ii,max_mnta)
{
		#{{{get the MNTA value of KGRN input file		
		num_ele1=split(string,array,"|")
		for (ii in array)
		{
				array[ii]=gensub(/([[:alpha:]]+)([[:digit:]]+[\.]?[[:digit:]]*)/,"\\1%\\2#","g",array[ii])
				gsub(/#+$/,"",array[ii])
		}
		for (i in array)
		{
				num_ele1=split(array[i],brray,"#")
				max_mnta=_max(max_mnta,num_ele1)
		}
		return max_mnta
		#}}}		
}

function  v(value,default_val)
{
		#{{{default value function		
		if (value == ""){value=default_val}
		return value
		#}}}		
}

function divide(string,elem,conc,cut1,cut2,array1,array2,i)
{
		#{{{!!!!	totsp need convert to local variable	
		totsp=split(string,array1,cut1)
		for (i in array1)
		{   
				split(array1[i],array2,cut2) 
				elem[i]=array2[1]
				conc[i]=array2[2]
		} 
		#}}}	   	
}

function SetPath(OPT)
{
		#{{{ set PATH for KGRN & KFCD
		#ENVIRON["EMTO_PATH"]="/home/levibox/EMTO"
		if("EMTO_PATH" in ENVIRON )
		{PATH["EMTO"]=ENVIRON["EMTO_PATH"]}else{_message("e","EMTO_PATH not be set");exit 1}

		PATH["BMDL"]=PATH["EMTO"]"/bmdl"
		PATH["KSTR"]=PATH["EMTO"]"/kstr"
		PATH["SHAP"]=PATH["EMTO"]"/shape"
		#PATH["PROJ"]=PATH["EMTO"]"/"ProjectName"/"
		if(OPT=="KGRN")
		{
				FOR001=PATH["KSTR"]"/smx/"rva["STR"]".tfh"
				FOR004=PATH["BMDL"]"/mdl/"rva["STR"]".mdl"		
				#FOR001=../kstr/smx/fcc.tfh
				#FOR001=../kstr/smx/fcc30.tfh
				#DIR002=pot/
				#DIR003=pot/
				#FOR004=../bmdl/mdl/fcc.mdl
				#DIR006=
				#DIR009=pot/
				#DIR010=chd/
				#DIR011=/tmp/
		}
		if(OPT=="KFCD")
		{
				DIR001=PATH["KSTR"]"/smx/"
				DIR002="./chd/"
				DIR003=PATH["SHAP"]"/shp/"
				DIR004=PATH["BMDL"]"/mdl/"
				STRNAM=rva["STR"]
				#DIR001=../kstr/smx/
				#DIR002=../kgrn/chd/
				#DIR003=../shape/shp/
				#DIR004=../bmdl/mdl/
				#DIR006=./
		}		

		return 0
		#}}}
}
